package com.eastedu.common.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * 〈〉
 *
 * @author ZHISHUAI.ZHANG
 * @since 2021 /7/30
 */
@Slf4j
public class SchoolGroupMappingUtil {

    /**
     * 校级名称映射
     */
    private static final Map<String, String> NAME_MAPPINGS = new HashMap<>();

    /**
     * 学校和校级映射
     */
    private static final MultiValueMap<String, String> ID_MAPPINGS = new LinkedMultiValueMap<>();

    static {
        try {
            read("classpath:mapping/schoolGroupName", line -> addName(line.split("\t")));
            read("classpath:mapping/schoolGroupId", line -> addId(line.split("\t")));
            /// ID_MAPPINGS.forEach((k, v) -> {
            ///     if (v.size() > 1) {
            ///         // throw new ServiceException("学校【" + k + "】存在多个校级");
            ///     }
            /// });
            /// log.info("初始化完成");

            /// ID_MAPPINGS.forEach((k, v) -> {
            ///     String a = "UPDATE t_basic_resource SET school_group_id = " + Long.parseLong(v.get(0)) + "  WHERE sync_state = 0 and source_org_id = \"" + k + "\";";
            ///     System.out.println(a);
            /// });
        } catch (IOException e) {
            log.error("配置文件读取异常", e);
        }
    }

    private static void read(String resourcePath, Consumer<String> consumer) throws IOException {
        final List<String> lines = readLines(resourcePath);
        if (CollectionUtils.isEmpty(lines)) {
            return;
        }
        lines.forEach(consumer);
    }

    private static void addId(String[] split) {
        ID_MAPPINGS.add(split[0], split[1]);
    }

    private static void addName(String[] split) {
        NAME_MAPPINGS.put(split[0], split[1]);
    }

    private static List<String> readLines(String resourcePath) throws IOException {
        return FileUtils.readLines(ResourceUtils.getFile(resourcePath), StandardCharsets.UTF_8);
    }

    /**
     * Mapping name string.
     *
     * @param schoolGroupId the school group id
     * @return the string
     */
    public static String mappingName(String schoolGroupId) {
        return NAME_MAPPINGS.get(schoolGroupId);
    }

    /**
     * Mapping ids set.
     *
     * @param organizationIds the organization ids
     * @return the set
     */
    public static Set<String> mappingIds(Set<String> organizationIds) {
        if (CollectionUtils.isEmpty(organizationIds)) {
            return Collections.emptySet();
        }
        return organizationIds.stream().flatMap(o -> ID_MAPPINGS.getOrDefault(o, Collections.emptyList()).stream())
                .filter(Objects::nonNull).map(String::valueOf).collect(Collectors.toSet());
    }

    /**
     * Mapping id long.
     *
     * @param organizationId the organization id
     * @return the long
     */
    public static Long mappingId(String organizationId) {
        final List<String> groupIds = ID_MAPPINGS.getOrDefault(organizationId, Collections.emptyList());
        if (groupIds.size() == 1) {
            return Long.valueOf(groupIds.get(0));
        }
        return 0L;
    }
}